// 模拟商品数据
const products = [
    { id: 1, name: 'Xiaomi15', price: 4999, image: 'img/xiaomi15.png' },
    { id: 2, name: 'Xiaomi15Ultra', price: 6499, image: 'img/xiaomi15Ultra.png' },
    { id: 3, name: 'Turbo4', price: 1999, image: 'img/Turbo4.png' },
    { id: 4, name: 'Xiaomi MIXFold 4', price: 9999, image: 'img/xiaomiMIXFold4.png' },
    { id: 5, name: 'Xiaomi Civi 4 Pro', price: 2799, image: 'img/XiaomiCivi4Pro.png' },
];

// 购物车数据
let cart = [];

// 渲染商品
function renderProducts(products) {
    const productGrid = document.getElementById('product-grid');
    productGrid.innerHTML = products.map(product => `
        <div class="product" data-id="${product.id}">
            <img src="${product.image}" alt="${product.name}">
            <h3>${product.name}</h3>
            <p>¥${product.price.toFixed(2)}</p>
            <button class="btn add-to-cart">加入购物车</button>
        </div>
    `).join('');
}

// 更新购物车数量
function updateCartCount() {
    const cartCount = document.getElementById('cart-count');
    cartCount.textContent = cart.length;
}

// 添加商品到购物车
function addToCart(productId) {
    const product = products.find(p => p.id === productId);
    if (product) {
        cart.push(product);
        updateCartCount();
        alert(`${product.name} 已加入购物车！`);
    }
}

// 加载更多商品
function loadMoreProducts() {
    const moreProducts = [
        { id: 6, name: 'SU7', price: 27, image: 'img/SU7.png' },
        { id: 7, name: 'SU7', price: 23, image: 'img/SU7_2.png' },
    ];
    products.push(...moreProducts);
    renderProducts(products);
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);

    // 加入购物车按钮事件
    document.getElementById('product-grid').addEventListener('click', (e) => {
        if (e.target.classList.contains('add-to-cart')) {
            const productId = parseInt(e.target.closest('.product').dataset.id);
            addToCart(productId);
        }
    });

    // 加载更多按钮事件
    document.getElementById('load-more').addEventListener('click', loadMoreProducts);

    // 搜索功能
    document.getElementById('search-btn').addEventListener('click', () => {
        const query = document.getElementById('search-input').value.toLowerCase();
        const filteredProducts = products.filter(product => product.name.toLowerCase().includes(query));
        renderProducts(filteredProducts);
    });
});

// 自动轮播脚本
let currentSlide = 0;
const slides = document.querySelectorAll('.slide');

function showNextSlide() {
    // 移除当前激活状态
    slides[currentSlide].classList.remove('active');
    
    // 计算下一个幻灯片索引
    currentSlide = (currentSlide + 1) % slides.length;
    
    // 添加激活状态
    slides[currentSlide].classList.add('active');
}

// 每5秒切换一次（5000ms）
setInterval(showNextSlide, 5000);